package com.example.websocketdemo.Socket;

import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: basic
 * @description:
 *      @ServerEndpoint 这个注解有什么作用？
 *          这个注解用于标识作用在类上，它的主要功能是把当前类标识成一个WebSocket的服务端
 *          注解的值用户客户端连接访问的URL地址
 * @author: Cloud
 * @create: 2020/11/17 09:33:11
 */
@Slf4j
@ServerEndpoint("/websocket/{name}")
@Component
public class Websocket {

    // 与某个客户端对话，需要它来给客户端发送消息
    private Session session;

    // 标识当前客户端的名称
    private String name;

    // 用于存储当前所有的连接服务的客户端，这个对象是安全的
    private static ConcurrentHashMap<String,Websocket> websocketSet = new ConcurrentHashMap<>();

    @OnOpen
    public void OnOpen(Session session, @PathParam(value = "name")String name){
        this.session = session;
        this.name = name;
        websocketSet.put(name,this);
        log.info("[WebSocket] 新加入一个连接，用户名为: "+name+"，当前连接人数为：{}",websocketSet.size());
    }

    @OnClose
    public void OnClose(){
        websocketSet.remove(this.name);
        log.info("[WebSocket] 用户名："+name+"退出会话，当前连接人数为：{}",websocketSet.size());
    }

    @OnMessage
    public void OnMessage(String message){
        log.info("这里是服务端！");
        log.info("[WebSocket] 收到消息：{}",message);
        List<String> list = Splitter.onPattern("[,]").omitEmptyStrings().splitToList(message);
        String name = list.get(0);
        // 判定是否需要指定发送，具体规则自定义
        if (websocketSet.get(name) != null) {
            AppointSending(name, this.name+"说："+list.get(1));
        } else {
            GroupSending(message);
        }
    }

    // 群发
    public void GroupSending(String message){
        log.info("开始群发消息了！");
        log.info("[WebSocket] 当前连接人数为：{}",websocketSet.size());
        for (String name : websocketSet.keySet()) {
            try {
                websocketSet.get(name).session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 指定发送
    public void AppointSending(String name,String message){
        log.info("开始发消息给{}了！",name);
        log.info("[WebSocket] 当前连接人数为：{}",websocketSet.size());
        try {
            websocketSet.get(name).session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
